package com.wangjiacai.utils.web.validator;

import com.wangjiacai.utils.enums.ResultEnum;
import org.springframework.util.StringUtils;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = Password.PasswordValidator.class)
@SecureValid(errorMessageBy= Password.PasswordErrorMessage.class)
public @interface Password {

    String message() default "密码安全等级不够，需要数字和字母的组合";

    ResultEnum result() default ResultEnum.ParamsInvalid;

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    class PasswordValidator implements ConstraintValidator<Password,String> {

        private String regex;

        @Override
        public void initialize(Password phone) {
            regex = "(\\d+.*[a-zA-Z]+.*|[a-zA-Z]+.*\\d+.*)";
        }

        @Override
        public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
            if(StringUtils.isEmpty(value)) return false;
            if (value.matches(regex)) return true;
            return false;
        }
    }
    class PasswordErrorMessage implements SecureValid.ErrorMessage<Password> {
        @Override
        public ResultEnum resultEnum(Password phone) {
            return phone.result();
        }
    }
}
